from fastapi import APIRouter, Depends, UploadFile
from backend.library.response import success, fail
from backend.model.user import UserModel, NewUserInfo, UpdateUserInfo, UserIds, ResetPasword, ChangStatus
from backend.model.course import CourseModel
from backend.library.database import get_db
from backend.library.utils import md5
from backend.config import get_config
import time ,os
import uuid
import pandas as pd

router = APIRouter(prefix="/api/admin")

@router.get("/user/list", tags=['用户管理'], summary="用户列表")
def list(page:int=1, realname:str = "", role:int = 0, limit:int=10, db=Depends(get_db)):
    
    total, rows = UserModel.search_user(db, realname, role, page, limit)

    return success("OK", {"total":total, "rows": rows})

@router.post("/user/add", tags=['用户管理'], summary="用户添加")
def add(info:NewUserInfo, db=Depends(get_db)):
    
    r = UserModel.add_user(db, info.__dict__)
    if r:
        return success("添加成功")    
    else:
        return fail("添加失败")

@router.post("/user/edit", tags=['用户管理'], summary="用户修改")
def edit(info: UpdateUserInfo,db=Depends(get_db)):
    r = UserModel.update_user(db, info.id, info.__dict__)
    if r:
        return success("更新成功")    
    else:
        return fail("更新失败")

@router.post("/user/del", tags=['用户管理'], summary="用户删除")
def delete(idList: UserIds,db=Depends(get_db)):
    r = UserModel.del_user(db, idList.ids)
    if r:
        return success("删除成功")    
    else:
        return fail("删除失败")

@router.post("/user/resetpwd", tags=['用户管理'], summary="重置密码")
def resetpwd(info:ResetPasword,db=Depends(get_db)):
    # 查询用户信息
    user = UserModel.get_user_by_id(db, info.user_id)
    if user is None:
        return fail("用户不存在")
    # 判断旧密码是否正确
    # if md5(info.oldpassword) != user.password:
    #     return fail("原密码输入不正确")
        
    # 判断新密码是否正确
    if info.newpassword != info.newpassword2:
        return fail("用户两次输入的新密码不一致")

    # 更新密码
    r = UserModel.update_user(db, info.user_id, {"password":md5(info.newpassword)})
    if r:
        return success("更新成功")    
    else:
        return fail("更新失败")

    return success("OK")

@router.post("/user/change", tags=['用户管理'], summary="修改账号状态")
def change_status(info:ChangStatus,db=Depends(get_db)):
    r = UserModel.update_user(db, info.user_id, {"status":info.status})
    if r:
        return success("更新成功")    
    else:
        return fail("更新失败")


@router.post("/user/import", tags=['用户管理'], summary="用户导入")
def imports(file:UploadFile, db=Depends(get_db)):
    """
    文件上传，批量导入（支持txt,csv,xls格式）
    """
    config = get_config()
    #保存上传文件到upload文件夹下
    
    filename = file.filename.split(".")

    if filename[-1] not in ['xls','xlsx']:
        return fail("文件类型不正确")
    
    now = time.localtime()
    folder = config.root_path + "/frontend/upload/%04d%02d%02d/" % (now.tm_year, now.tm_mon, now.tm_mday)

    if not os.path.exists(folder):
        os.mkdir(folder)
    
    newFileName = folder + str(uuid.uuid4()) + "." + filename[-1]

    with open(newFileName, 'wb') as f:
        for chunk in iter(lambda: file.file.read(1024*1024*10), b''):
            f.write(chunk)

    #读文件，将文件中的数据生成数据库插入操作
    df = pd.read_excel(newFileName)

    for row in df.values:
        user = {
            'username': row[0],
            'realname': row[1],
            'password': md5(str(row[2])),
            'status': 1,
            'role': 3
        }
        UserModel.add_user(db, user)

    return success("OK")


@router.get("/course/list", tags=['课程管理'], summary="课程列表")
def list(page:int=1, course_name:str = "", limit:int=10, db=Depends(get_db)):
    

    total, rows = CourseModel.search(db, course_name, page, limit)

    return success("OK", {"total":total, "rows": rows})

@router.post("/course/add", tags=['课程管理'], summary="课程添加")
def add(info:NewUserInfo, db=Depends(get_db)):
    r = CourseModel.add(db, info.__dict__)
    if r:
        return success("添加成功")    
    else:
        return fail("添加失败")

@router.post("/course/edit", tags=['课程管理'], summary="课程修改")
def edit(info: UpdateUserInfo,db=Depends(get_db)):
    r = CourseModel.edit(db, info.id, info.__dict__)
    if r:
        return success("更新成功")    
    else:
        return fail("更新失败")

@router.post("/course/del", tags=['课程管理'], summary="课程删除")
def delete(idList: UserIds,db=Depends(get_db)):
    r = CourseModel.delete(db, idList.ids)
    if r:
        return success("删除成功")    
    else:
        return fail("删除失败")